package com.boat.sample.ddd.application.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boat.framework.base.exception.ServiceException;
import com.boat.framework.common.security.model.LoggedUser;
import com.boat.sample.ddd.api.dto.LoginReq;
import com.boat.sample.ddd.api.errorcode.DddErrCode;
import com.boat.sample.ddd.domain.system.entity.User;
import com.boat.sample.ddd.domain.system.repository.UserRepository;
import com.boat.sample.ddd.domain.system.service.UserService;
import com.boat.sample.ddd.infrastructure.client.SupportClient;
import com.boat.starter.satoken.utils.SaTokenUtils;
import com.boat.starter.satoken.utils.SaTokenUtils.LoginResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserAppService {
	@Autowired
	UserService userService;
	@Autowired
	UserRepository userRepository;
	@Autowired
	SupportClient supportClient;

	public LoginResult register(User user) {
		User userInfo = userService.register(user);
		LoggedUser loginUser = new LoggedUser();
		loginUser.setUserId(String.valueOf(userInfo.getId()));
		loginUser.setUserName(userInfo.getUserName());
		loginUser.setUserType(userInfo.getUserType());
		LoginResult loginResult = SaTokenUtils.login(loginUser, null);

//		OpenAccountReq openAccountReq = new OpenAccountReq();
//		openAccountReq.setUserId(user.getId());
//		openAccountReq.setName("zzzzzz");
//		supportClient.openAccount(openAccountReq);
//
//		// 跨系统调用
//		supportClient.sendSMS("12345677", "你已注册成功");
		return loginResult;
	}
	
	public LoginResult login(LoginReq loginReq) {
		User example = new User();
		example.setUserName(loginReq.getUserName());
		User userInfo = userRepository.getByExample(example);
		if (userInfo == null) {
			throw new ServiceException(DddErrCode.USER_NOT_FOUND);
		}
		
		LoggedUser loginUser = new LoggedUser();
		loginUser.setUserId(String.valueOf(userInfo.getId()));
		loginUser.setUserName(userInfo.getUserName());
		loginUser.setUserType(userInfo.getUserType());
		LoginResult loginResult = SaTokenUtils.login(loginUser, null);
		return loginResult;
	}

	// @Cached(name = "user", key = "#userId", cacheType = CacheType.REMOTE, expire
	// = 60)
	public User findUser(String userId) {
		log.info("查询用户");
		User example = new User();
		example.setId(userId);
		User user = userRepository.getByExample(example);
		// User user = userRepository.getById(userId);
		if (user == null) {
			throw new ServiceException(DddErrCode.USER_NOT_FOUND);
		}
		return user;
	}
}
